package gwtappcontainer.client.apps.videos.view;

import gwtappcontainer.client.ContainerUtil;
import gwtappcontainer.client.apps.IPresenter;
import gwtappcontainer.client.apps.videos.VideoRpcService;
import gwtappcontainer.client.apps.videos.VideoRpcServiceAsync;
import gwtappcontainer.shared.apps.videos.VideoProp;

import java.util.Map;
import java.util.logging.Logger;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;

public class Presenter implements IPresenter {

	private Logger logger;

	@Override
	public void render(final FlowPanel fp, Map<String, String> params) {
				
		fp.clear();
		fp.add(new HTML("Fetching video..."));	
		
		VideoRpcServiceAsync videoSvc = GWT.create(VideoRpcService.class);
		
		logger = ContainerUtil.getLogger(Presenter.class.getName());
		
		String tag = "";
		if (! params.isEmpty()) {
			if (params.containsKey("tag"))
				tag = params.get("tag");
		}
						
//		String tag = "20130202";
		videoSvc.getVideoProp(tag, new AsyncCallback<VideoProp>() {

			@Override
			public void onFailure(Throwable caught) {
				String errMessage = "Exception thrown by rpc." + caught.getMessage();
				logger.severe(errMessage + "\n" + caught.toString());			
				Window.alert(errMessage + 
						". Try reloading the page by clicking the refresh button in your browser");
				//to do : change to error dialog box							
			}

			@Override
			public void onSuccess(VideoProp result) {
				View view = new View();
				
				if (null == result)
					view.videoFrame.setHTML("<b>Error</b> - unable to load video");				
				else {
					view.title.setHTML(result.titleHtml);
					view.description.setHTML(result.descriptionHtml);
					
					if (result.enabled && ! result.videoFrameHtml.equals("")) {
						view.videoFrame.setHTML(result.videoFrameHtml);						
						view.appeal.setHTML(result.appealHtml);
					} else {
						view.videoFrame.setHTML(result.msgWhenVideoNotAvailableHtml);
					}					
				}
				
				fp.clear();
				fp.add(view);
			}
		});					
	}		
}
